package com.dayaokeji.rhythmschoolstudent.client.common.exam;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.BlankSubjectFragment;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.ChooseSubjectFragment;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.JudgmentProblemFragment;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.QuestionAndAnswerFragment;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.utils.AnswerCallback;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.subject_type.utils.SubjectTypeUtil;
import com.dayaokeji.rhythmschoolstudent.utils.DialogUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ObjectUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.rhythmschoolstudent.wiget.SubjectListDialog;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.ExamApi;
import com.dayaokeji.server_api.domain.CommitExam;
import com.dayaokeji.server_api.domain.Exam;
import com.dayaokeji.server_api.domain.ExamQuestion;
import com.dayaokeji.server_api.domain.SubjectAnswer;
import com.dayaokeji.server_api.domain.UpdateExam;
import com.dayaokeji.server_api.domain.UserInfo;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 答题
 */
public class AnswerActivity extends BaseActivity implements AnswerCallback  {

    public static final String EXTRA_EXAM_ID = "exam_id";
    public static final String EXTRA_TEST_NAME = "test_name";
    public static final String EXTRA_SHOW_EXAM_RESULT = "exam_result";
    public static final String EXTRA_EXAM_ENTITY = "exam_entity";
    public static final String EXTRA_IS_QUESTION_AND_ANSWER = "extra_question_and_answer";

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.fl_single_topic)
    FrameLayout flSingleTopic;
    @BindView(R.id.btn_submit_or_next)
    Button btnSubmitOrNext;
    @BindView(R.id.tv_subject_pre)
    TextView tvSubjectPre;
    @BindView(R.id.ll_subject_opt)
    LinearLayout llSubjectOpt;

    private List<ExamQuestion> examQuestionList = new ArrayList<>();
    private final List<SubjectAnswer> subjectAnswers = new ArrayList<>();

    private static final ExamApi examApi = ApiUtils.getApi(ExamApi.class);
    private Call<ServerResponse<List<ExamQuestion>>> examQuestionCall;
    private Call<ServerResponse<Void>> commitExamCall;

    private int examId;
    private String testName;
    private UserInfo userInfo;
    private boolean isExamResult;
    private Exam exam;
    private boolean isQuestionAndAnswer;
    private boolean isShowSubject = false;
    private int currentSubjectIndex = 0;
    private SubjectListDialog subjectListDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_answer);
        setSupportActionBar(toolbar);
        examId = getIntent().getIntExtra(EXTRA_EXAM_ID, -1);
        testName = getIntent().getStringExtra(EXTRA_TEST_NAME);
        exam = (Exam) getIntent().getSerializableExtra(EXTRA_EXAM_ENTITY);
        isExamResult = getIntent().getBooleanExtra(EXTRA_SHOW_EXAM_RESULT, false);
        isQuestionAndAnswer = getIntent().getBooleanExtra(EXTRA_IS_QUESTION_AND_ANSWER, false);
        userInfo = UserUtils.getUserInfo();
        if (examId == -1 && userInfo != null && !TextUtils.isEmpty(userInfo.getId())) {
            ToastUtils.warning(R.string.data_incorrect);
            ActivityStackManager.finish();
        }
        init();
    }

    private void init() {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(testName);
        }
        if (isExamResult) {
            queryStudentAnswerInfo();
        }else{
            requestExamQuestion();
        }
        subjectListDialog = SubjectListDialog.Companion.newInstance(examQuestionList);
    }


    @SuppressLint("SetTextI18n")
    private void showSubject(ExamQuestion examQuestion, int position) {
        flSingleTopic.setVisibility(View.VISIBLE);
        isShowSubject = true;
        btnSubmitOrNext.setText("下一题");
        currentSubjectIndex = position;
        changeSubjectIndex();
        replaceFragment(examQuestion);
    }

    private void replaceFragment(ExamQuestion examQuestion) {
        if (isExamResult) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_single_topic, SubjectResultFragment.Companion.newInstance(examQuestion)).commit();
        }else{
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_single_topic, subjectFragmentByType(examQuestion)).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.answer, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.menu_exam_submit).setVisible(!isExamResult);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_exam_submit:
                examSubmitDialog();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick({R.id.iv_show_list,R.id.btn_submit_or_next,R.id.tv_subject_pre})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_show_list:
                subjectListDialog.show(getSupportFragmentManager(), "subject_items");
                subjectListDialog.setItemClickListener(new SubjectListDialog.ItemClickListener() {
                    @Override
                    public void click(@NotNull ExamQuestion subject,int position) {
                        showSubject(subject, position);
                    }
                });
                break;
            case R.id.btn_submit_or_next:
                nextSubject();
                break;
            case R.id.tv_subject_pre:
                preSubject();
                break;
        }
    }

    private void preSubject() {
        if ((currentSubjectIndex+1) > 0) {
            currentSubjectIndex = currentSubjectIndex - 1;
            changeSubjectIndex();
            subjectListDialog.setCurrentPosition(currentSubjectIndex);
            try{
                if (currentSubjectIndex < examQuestionList.size()) {
                    ExamQuestion examQuestion = examQuestionList.get(currentSubjectIndex);
                    replaceFragment(examQuestion);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void nextSubject() {
        int size = examQuestionList.size();
        if ((currentSubjectIndex+1) < size) {
            currentSubjectIndex = currentSubjectIndex + 1;
            changeSubjectIndex();
            subjectListDialog.setCurrentPosition(currentSubjectIndex);
            ExamQuestion examQuestion = examQuestionList.get(currentSubjectIndex);
            replaceFragment(examQuestion);
        }
    }

    private void changeSubjectIndex() {
        if ((currentSubjectIndex+1) == examQuestionList.size()) {
            btnSubmitOrNext.setEnabled(false);
        }else{
            btnSubmitOrNext.setEnabled(true);
        }
        if (currentSubjectIndex == 0) {
            tvSubjectPre.setEnabled(false);
        }else{
            tvSubjectPre.setEnabled(true);
        }
    }


    /**
     * 获取题目列表
     */
    private void requestExamQuestion() {
        examQuestionCall = examApi.queryExamQuestion(examId, userInfo.getId());
        examQuestionCall.enqueue(new ServerCallback<List<ExamQuestion>>(this,"正在下载试题...") {
            @Override
            public void onResponse(boolean success, ServerResponse<List<ExamQuestion>> response) {
                if (success) {
                    examQuestionList.addAll(response.getBody());
                    ExamQuestion examQuestion = examQuestionList.get(currentSubjectIndex);
                    showSubject(examQuestion,currentSubjectIndex);
                }
            }
        });
    }

    /**
     * 获取题目列表
     */
    private void queryStudentAnswerInfo() {
        examQuestionCall = examApi.queryStudentAnswerInfo(examId, userInfo.getId());
        examQuestionCall.enqueue(new ServerCallback<List<ExamQuestion>>(this,"正在下载试题...") {
            @Override
            public void onResponse(boolean success, ServerResponse<List<ExamQuestion>> response) {
                if (success) {
                    examQuestionList.addAll(response.getBody());
                    ExamQuestion examQuestion = examQuestionList.get(currentSubjectIndex);
                    showSubject(examQuestion,currentSubjectIndex);
                }
            }
        });
    }

    private void examSubmitDialog() {
        DialogUtils.getAlertDialog(this, "提示", "是否提交试卷,并结束考试？", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                examSubmit();
            }
        });
    }

    /**
     * 提交试卷
     */
    private void examSubmit() {
        CommitExam commitExam = new CommitExam();
        commitExam.setId(examId);
        commitExam.setExamAnswerList(subjectAnswers);
        Logger.d(commitExam.toString());
        commitExamCall = examApi.commitExam(commitExam);
        commitExamCall.enqueue(new ServerCallback<Void>(this,"正在交卷中...") {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    ToastUtils.success("提交成功");
                    EventBus.getDefault().post(new UpdateExam());
                    ActivityStackManager.finish();
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        if (examQuestionCall != null) {
            examQuestionCall.cancel();
        }
        if (commitExamCall != null) {
            commitExamCall.cancel();
        }
        super.onDestroy();
    }

    @Override
    public void callback(SubjectAnswer subjectAnswer) {

        if (subjectAnswers.contains(subjectAnswer)) {
            final int indexOf = subjectAnswers.indexOf(subjectAnswer);
            subjectAnswers.remove(indexOf);
            subjectAnswer.setAnswer(TextUtils.isEmpty(subjectAnswer.getAnswer())?"":subjectAnswer.getAnswer());
            subjectAnswers.add(subjectAnswer);
        }else{
            subjectAnswer.setAnswer(TextUtils.isEmpty(subjectAnswer.getAnswer())?"":subjectAnswer.getAnswer());
            subjectAnswers.add(subjectAnswer);
        }
        for (ExamQuestion examQuestion : examQuestionList) {
            if (ObjectUtils.equals(subjectAnswer.getExamQuestionId(), examQuestion.getId())) {
                examQuestion.setSubjectAnswer(subjectAnswer);
            }
        }
    }

    private Fragment subjectFragmentByType(ExamQuestion examQuestion) {
        final int type = examQuestion.getType();
        switch (type) {
            case SubjectTypeUtil.SINGLE_CHOOSE:
                return ChooseSubjectFragment.newInstance(examQuestion).setShowExamResult(false);
            case SubjectTypeUtil.MULTIPLE_CHOOSE:
                return ChooseSubjectFragment.newInstance(examQuestion).setShowExamResult(false);
            case SubjectTypeUtil.QUESTION_AND_ANSWER:
                return QuestionAndAnswerFragment.newInstance(examQuestion).setShowExamResult(false);
            case SubjectTypeUtil.BLANK_SUBJECT:
                return BlankSubjectFragment.newInstance(examQuestion).setShowExamResult(false);
            case SubjectTypeUtil.JUDGMENT_PROBLEM:
                return JudgmentProblemFragment.newInstance(examQuestion).setShowExamResult(false);
            default:
                return null;
        }
    }


}
